<template>
  <div class="flex items-center justify-between h-12 leading-12 px-3 border-b border-gray-400 border-opacity-30">
    <div class="bold" style="font-size: 14px;">标签类型</div>
    <VButton auth="/base/label/add-type" link type="primary" @click="add()">添加</VButton>
  </div>
  <div class="flex flex-col label-type">
    <div class="flex gap-2 px-3 py-2 border-r-2"
      :class="d.lt_id === activeName ? 'text-blue-500 border-blue-600 base-menu-bg-color' : 'border-transparent hover:bg-gray-500 hover:bg-opacity-10'"
      v-for="(d, i) in list" :key="i" @click="activeName = d.lt_id">
      <div class="flex-1 cursor-pointer text-inherit">{{ d.name }}</div>
      <VButton auth="/base/label/update-type" icon="edit" link type="primary" class="ml-auto" @click="add(d.lt_id)"></VButton>
      <VButton auth="/base/label/delete-type" icon="delete" link type="danger" class="m-0" :loading="loadings.remove"
        @click="remove(d.lt_id)"></VButton>
    </div>
  </div>
  <Add ref="addRef" @success="query" />
</template>

<script setup>
import { watch } from 'vue';
import api from '../../api'
import Add from './Add'
import { ElMessage, ElMessageBox } from 'element-plus'
let loadings = reactive({})
const list = ref([])
const addRef = ref()
const activeName = ref('')
const emit = defineEmits(['change'])

const query = () => {
  return api.typeList().then(res => {
    list.value = res.data
    if (!list.value.some(d => d.lt_id === activeName.value)) {
      activeName.value = list.value[0].lt_id
    }
    return res.data
  })
}
query()

const add = (lt_id) => {
  addRef?.value.open(lt_id)
}

const remove = (lt_id) => {
  ElMessageBox.confirm('是否确认删除？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(() => {
      loadings.remove = true
      api.deleteType({ lt_ids: [lt_id] }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(() => {
        loadings.remove = false
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消操作', })
    })
}

watch(
  () => activeName.value,
  (val) => emit('change', val)
)
</script>

<style lang="scss">
.label-type {
  font-size: 12px;
  color: #666;
}

.base-menu-bg-color{
  background-color: var(--base-menu-bg-color);
}
</style>